package com.ug.common.utils;


import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ProcessUtils {
    public static List<String> runPythonScript(String fileLoad,String project,String name) throws IOException, InterruptedException {
        List<String> command = new ArrayList<>();
        List<String> arguments = new ArrayList<>();
        arguments.add("--source");
        arguments.add(fileLoad);
        arguments.add("--project");
        arguments.add(project);
        arguments.add("--name");
        arguments.add(name);
        arguments.add("--hide-conf");
        arguments.add("--exist-ok");
        arguments.add("--max-det");
        arguments.add("1");

        String[] processArgs = new String[arguments.size() + 3];
        processArgs[0] = "cmd.exe";
        processArgs[1] = "/c";
        processArgs[2] = "C:\\Users\\admin\\Desktop\\workSpace\\UG\\UG\\ug-backend\\src\\main\\resources\\run_python.bat";
        System.arraycopy(arguments.toArray(), 0, processArgs, 3, arguments.size());

        ProcessBuilder processBuilder = new ProcessBuilder(processArgs);

        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] list = line.split(" ");
            if(list[0].equals("image")){
                command.add(line);
            }
        }
        int exitCode = process.waitFor();

        if (exitCode == 0) {
            return command;
        } else {
            throw new RuntimeException("Python脚本执行失败，退出码：" + exitCode);
        }
    }
}
